//
//  BKODAliManager+BKOrder.m
//  bestkeep
//
//  Created by yons on 16/12/15.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "BKODAliManager+BKOrder.h"
#import "BKOrderPayForResultsViewController.h"

@implementation BKODAliManager (BKOrder)

- (void)orderPaymentResultWithDidFinishLaunching:(NSDictionary *)launchOptions
{
    
    
    id url = launchOptions[UIApplicationLaunchOptionsURLKey];
    
    if (!launchOptions || !launchOptions.allKeys.count || !url || ![url isKindOfClass:[NSURL class]]) {
        return;
    }
    
    
    if ([[url host] isEqualToString:@"safepay"])
    {
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {

            NSString *resultStatus = resultDic[@"resultStatus"];
            
            UIViewController *rootVC =[UIApplication sharedApplication].keyWindow.rootViewController;
            if (rootVC && [rootVC isKindOfClass:NSClassFromString(@"RootTabBarController")])
            {
                UITabBarController *tabBar = (UITabBarController *)rootVC;
                if (tabBar.viewControllers && tabBar.viewControllers.count)
                {
                    UIViewController *subVC = tabBar.viewControllers.firstObject;
                    if (subVC && [subVC isKindOfClass:NSClassFromString(@"RootNavigationController")])
                    {
                        UINavigationController *navigationVC = (UINavigationController *)subVC;
                        BKOrderPayForResultsViewController *payRstVC = [[BKOrderPayForResultsViewController alloc] init];
                        if ([resultStatus isEqualToString:@"9000"])
                        {
                            payRstVC.success = YES;
                        }
                        else
                        {
                            payRstVC.enterForeground = YES;
                        }
                        [navigationVC pushViewController:payRstVC animated:YES];
                    }
                }
            }
            
        }];
    }
    
}

- (void)orderPaymentResultWithOpenUrl:(NSURL *)url
{

    if (![[UIApplication sharedApplication] keyWindow] || ![[[UIApplication sharedApplication] keyWindow] rootViewController])
    {
        return;
    }
    
    if ([url.host isEqualToString:@"safepay"])
    {
        __weak typeof(self)weakSelf = self;
        
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic)
        {
            if (weakSelf.delegate && [weakSelf.delegate conformsToProtocol:@protocol(BKODAliManagerDelegate)])
            {
                [weakSelf.delegate ODWAliManagerDidRecvPayResult:resultDic];
            }
        }];
    }
}

@end
